package com.jamal2362.apktool.task;

import android.content.Context;
import brut.util.OS;
import java.io.File;
import com.jamal2362.apktool.R;
import com.jamal2362.apktool.fragment.files.Refreshable;
import com.jamal2362.apktool.util.FileUtils;

public class CopyTask extends AbstractTask
{
	private Context context;
	private String targetDir;
	private boolean cutFile;
	boolean showDialog;
	private int title;

	public CopyTask(Context ctx, String target, boolean cut, Refreshable refresh)
	{
		super(ctx, refresh);
		this.context = ctx;
		this.targetDir = target;
		this.cutFile = cut;
		this.showDialog = false;
		this.title = (cut ? R.string.moving : R.string.copying);
	}

	@Override
	protected int getTitle()
	{
		return title;
	}

	@Override
	protected boolean process(File f)
	{
		info((cutFile ? R.string.moving_file : R.string.build_copy_file), f.getAbsolutePath());
		if (!f.exists())
		{
			warning(R.string.file_not_found, f.getAbsolutePath());
			this.showDialog = true;
			return false;
		}
		try
		{
			File d =  new File(targetDir);
			if (!d.exists() && !d.mkdirs())
			{
				warning(R.string.output_directory_not_extsts, targetDir);
				this.showDialog = true;
				return false;
			}
			if (!d.isDirectory())
			{
				warning(R.string.not_directory, targetDir);
				this.showDialog = true;
				return false;
			}
			boolean success = false;
			boolean isdir = f.isDirectory();
			String name = f.getName();
			if (targetDir.startsWith(f.getAbsolutePath()) && isdir)
				cutFile = false;
				
			int e = name.lastIndexOf('.');
			if (e >= 0)
			{
				name = FileUtils.genName(context, targetDir, name.substring(0, e), name.substring(e), 0);
			}
			else
			{
				name = FileUtils.genName(context, targetDir, name, "", 0);
			}
			File out = new File(d, name);
			if (out.equals(f))
				return true;
			if (isdir)
			{
				OS.cpdir(f, out);
			}
			else
			{
				success = FileUtils.copyFiles(f, out);
			}
			if (success && cutFile)
			{
				if (isdir)
					OS.rmdir(f);
				else
					f.delete();
			}
			info(title, context.getString(R.string.complete).toLowerCase());
			return success;
		}
		catch (Exception e)
		{
			warning(R.string.errorf, e.getMessage());
			this.showDialog = true;
			return false;
		}
	}

	@Override
	protected boolean shouldShowFinishDialog()
	{
		return this.showDialog;
	}

	@Override
	protected void onPostExecute(Boolean result)
	{
		super.onPostExecute(result);
	}
}
